const log4js = require('log4js')

/**
 * log4js配置
 */
log4js.configure({
    replaceConsole: true,
    appenders: {
        // 控制台输出
        stdout: {
            type: 'stdout'
        },
        // express请求日志
        request: {
            type    : 'dateFile',
            filename: 'logs/request/',
            pattern : 'request-yyyy-MM-dd.log',
            alwaysIncludePattern: true
        },
        // 错误日志
        error: {
            type    : 'dateFile',
            filename: 'logs/error/',
            pattern : 'error-yyyy-MM-dd.log',
            alwaysIncludePattern: true
        },
        // 普通日志
        info: {
            type    : 'dateFile',
            filename: 'logs/info/',
            pattern : 'info-yyyy-MM-dd.log',
            alwaysIncludePattern: true
        }
    },
    categories: {
        // appenders:取appenders项, level:设置级别
        default:    { appenders: ['stdout', 'request','info']   , level: 'debug' },
        error:        { appenders: ['stdout', 'error']              , level: 'error' },
        info:       { appenders: ['stdout', 'info']             , level: 'info' },
        request:    { appenders: ['stdout', 'request']          , level: 'debug'}
    }
})
 
/**
 * name 取值categories里的某一键值
 */
exports.getLogger = function (name) {   
    return log4js.getLogger(name || 'default')
}
 
/**
 * 用来与express结合,记录请求日志
 */
exports.useLogger = function (app, logger) {
    app.use(log4js.connectLogger(logger || log4js.getLogger('default'), {
        // 自定义输出格式
        format: '[:remote-addr :method :url :status :response-timems][:referrer HTTP/:http-version :user-agent]'
    }))
}